package com.mushuilingfeng.ddd.user.infrastructure.base;

import com.mushuilingfeng.ddd.user.domain.base.service.Ii8nService;
import com.mushuilingfeng.ddd.user.infrastructure.utils.HttpServletRequestUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

/**
 * @author
 * @date 2024/9/19
 */
@Service
public class Ii8nServiceImpl implements Ii8nService {
    @Resource
    private Environment environment;
    @Value("${ii8n.default.lang}")
    private String defaultLang;

    @Override
    public String getMessage(String code, String defaultMessage) {
        HttpServletRequest currentRequest = HttpServletRequestUtil.getCurrentRequest();
        String lang = null;
        if (null != currentRequest) {
            lang = currentRequest.getHeader("lang");
        }
        if (null == lang) {
            lang = defaultLang;
        }
        return getMessage(code, lang, defaultMessage);
    }

    @Override
    public String getMessage(String code, String lang, String defaultMessage) {
        String value = environment.getProperty(code + "." + lang);
        if (null == value && !defaultLang.equals(lang)) {
            value = environment.getProperty(code + "." + defaultLang);
        }
        return null == value ? defaultMessage : value;
    }

}
